package org.mog.music.controller;

import cn.hutool.json.JSONUtil;
import context.MusicInfoContext;
import dto.MusicPageDTO;
import entity.pojo.Music;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.mog.file.config.MinIOConfigProperties;
import org.mog.file.service.FileStorageService;
import org.mog.music.mapper.MusicMapper;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.net.URL;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/temp")
@RequiredArgsConstructor
@Api(tags = "临时接口")
public class TempController {
    private final MusicMapper musicMapper;
    private final FileStorageService fileStorageService;
    private final MinIOConfigProperties minIOConfigProperties;
    private final RestTemplate restTemplate;

    @ApiOperation("修改歌曲url临时接口")
    @PutMapping("/update")
    public void updateUrl() throws IOException {
        MusicPageDTO dto = MusicPageDTO.builder()
                .myself(0)
                .page(1)
                .pageSize(300)
                .build();
        List<Music> musicList = musicMapper.getShareMusicList(dto);

        for (Music music : musicList) {
            String url = "https://www.hhlqilongzhu.cn/api/dg_kugouSQ.php?msg={}&n=1&num=1&type=json&quality=128";
            url = url.replaceAll("\\{}", (music.getName() + music.getSinger()).replaceAll(" ", ""));

            CloseableHttpClient client = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet(url);

            CloseableHttpResponse response = client.execute(httpGet);

            HttpEntity entity = response.getEntity();
            String res = EntityUtils.toString(entity);
            EntityUtils.consume(entity);

            HashMap map = JSONUtil.toBean(res, HashMap.class);
            String musicUrl = (String) map.get("music_url");

            System.out.println(music.getName() + "：" + musicUrl);

            musicMapper.updateAudioTemp(Math.toIntExact(music.getId()), musicUrl);
        }
        System.out.println("ok!!");
    }

    @ApiOperation("将数据库中链接对应的mp3文件存入minio")
    @GetMapping("/save")
    public void save2Minio() throws Exception {
        //查询所有音乐
        MusicPageDTO dto = MusicPageDTO.builder()
                .myself(0)
                .page(1)
                .pageSize(300)
                .build();
        List<Music> musicList = musicMapper.getShareMusicList(dto);
        String musicUrl;
        for (Music music : musicList) {
            System.out.println("准备上传 " + music.getSinger() + "-" + music.getName() + ".mp3");
            musicUrl = music.getAudio();
            InputStream is = new URL(musicUrl).openStream();

            String newUrl = fileStorageService.uploadAudioFile(
                    (StringUtils.isBlank(music.getSinger()) ?
                            MusicInfoContext.OTHER : music.getSinger()) + "/"
                            + (StringUtils.isBlank(music.getAlbumName())
                            ? MusicInfoContext.OTHER : music.getAlbumName()),
                    (music.getSinger() + "-" + music.getName() + ".mp3").replaceAll(" ", ""),
                    is);

            System.out.println("上传成功：" + newUrl);

            musicMapper.updateAudioTemp(Math.toIntExact(music.getId()), newUrl);

            is.close();
        }
        System.out.println("ok");
    }

    @ApiOperation("查看minio中是否存在文件")
    @GetMapping("/checkExist")
    public boolean checkExist(String objName) throws Exception {
        System.out.println("查看minio中是否存在文件：" + objName);
        return fileStorageService.isExist(minIOConfigProperties.getBucket(),
                objName);
    }
}
